package ${package};

import jakarta.annotation.Resource;
import org.jl.demo.model.${baseRequestMapping}.${className};
import org.jl.demo.service.${baseRequestMapping}.${className}Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/${baseRequestMapping}")
public class ${className}Controller {

    @Resource
    private ${className}Service ${baseRequestMapping}Service;

    @GetMapping("/")
    public String index(Model model, @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "5") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<${className}> ${baseRequestMapping}s = ${baseRequestMapping}Service.page(pageable);
        model.addAttribute("${baseRequestMapping}s", ${baseRequestMapping}s);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", ${baseRequestMapping}s.getTotalPages());
        return "/${baseRequestMapping}/index";
    }

    @GetMapping("/add")
    public String addForm(Model model) {
        model.addAttribute("${baseRequestMapping}", new ${className}());
        return "/${baseRequestMapping}/add";
    }

    @PostMapping("/add")
    public String add(@ModelAttribute ${className} ${baseRequestMapping}) {
        ${baseRequestMapping}Service.insert(${baseRequestMapping});
        return "redirect:/${baseRequestMapping}/";
    }

    @GetMapping("/edit/{id}")
    public String editForm(@PathVariable Long id, Model model, @RequestParam(defaultValue = "0") int page) {
        model.addAttribute("${baseRequestMapping}", ${baseRequestMapping}Service.getById(id).orElse(new ${className}()));
        model.addAttribute("currentPage", page);
        return "/${baseRequestMapping}/edit";
    }

    @PostMapping("/edit/{id}")
    public String edit(@PathVariable Long id, @ModelAttribute ${className} ${baseRequestMapping}Detail, @RequestParam(defaultValue = "0") int page) {
        ${baseRequestMapping}Service.update(id, ${baseRequestMapping}Detail);
        return "redirect:/${baseRequestMapping}/?page=" + page;
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Long id) {
        ${baseRequestMapping}Service.delete(id);
        return "redirect:/${baseRequestMapping}/";
    }
}